﻿#region File and License Information
/*
<File>
	<License Type="BSD">
		Copyright © 2009 - 2012, Outcoder. All rights reserved.
	
		This file is part of Calcium (http://calciumsdk.net).

		Redistribution and use in source and binary forms, with or without
		modification, are permitted provided that the following conditions are met:
			* Redistributions of source code must retain the above copyright
			  notice, this list of conditions and the following disclaimer.
			* Redistributions in binary form must reproduce the above copyright
			  notice, this list of conditions and the following disclaimer in the
			  documentation and/or other materials provided with the distribution.
			* Neither the name of the <organization> nor the
			  names of its contributors may be used to endorse or promote products
			  derived from this software without specific prior written permission.

		THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
		ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
		WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
		DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
		DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
		(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
		LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
		ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
		(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
		SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
	</License>
	<Owner Name="Daniel Vaughan" Email="danielvaughan@outcoder.com" />
	<CreationDate>2011-11-17 15:50:52Z</CreationDate>
</File>
*/
#endregion

using System;
using System.Collections.Generic;
using System.Diagnostics;

using Outcoder.Data.Serialization;

namespace Outcoder.ComponentModel.StatePreservation
{
	public class ViewState
	{
		readonly object transientStateLock = new object();
		readonly Dictionary<string, IStateAccessor> transientState
										= new Dictionary<string, IStateAccessor>();
		readonly object persistentStateLock = new object();
		readonly Dictionary<string, IStateAccessor> persistentState
										= new Dictionary<string, IStateAccessor>();

		public void RegisterState<T>(
			string stateKey,
			Func<T> getterFunc,
			Action<T> setterAction,
			ApplicationStateType stateType)
		{
			ArgumentValidator.AssertNotNull(stateKey, "propertyName");
			ArgumentValidator.AssertNotNull(getterFunc, "propertyGetterFunc");
			ArgumentValidator.AssertNotNull(setterAction, "propertySetterAction");

			if (stateType == ApplicationStateType.Persistent)
			{
				lock (persistentStateLock)
				{
					persistentState[stateKey]
						= new Accessor<T>(getterFunc, setterAction);
				}
			}
			else
			{
				lock (transientStateLock)
				{
					transientState[stateKey]
						= new Accessor<T>(getterFunc, setterAction);
				}
			}
		}

		public void DeregisterState(
			string stateKey,
			ApplicationStateType? applicationStateType)
		{
			ArgumentValidator.AssertNotNull(stateKey, "stateKey");

			if (applicationStateType.HasValue)
			{
				if (applicationStateType == ApplicationStateType.Persistent)
				{
					DeregisterPersistentState(stateKey);
				}
				else
				{
					DeregisterTransientState(stateKey);
				}
			}
			else
			{
				DeregisterPersistentState(stateKey);
				DeregisterTransientState(stateKey);
			}
		}

		void DeregisterTransientState(string stateKey)
		{
			ArgumentValidator.AssertNotNull(stateKey, "stateKey");

			lock (transientStateLock)
			{
				transientState.Remove(stateKey);
			}
		}

		void DeregisterPersistentState(string stateKey)
		{
			ArgumentValidator.AssertNotNull(stateKey, "stateKey");

			lock (persistentStateLock)
			{
				persistentState.Remove(stateKey);
			}
		}

		public void SaveTransientState(IDictionary<string, object> stateDictionary)
		{
			SaveState(stateDictionary, transientState, transientStateLock);
		}

		public void SavePersistentState(IDictionary<string, object> stateDictionary)
		{
			SaveState(stateDictionary, persistentState, persistentStateLock);
		}

		public void LoadTransientState(IDictionary<string, object> stateDictionary)
		{
			LoadState(stateDictionary, transientState, transientStateLock);
		}

		public void LoadPersistentState(IDictionary<string, object> stateDictionary)
		{
			LoadState(stateDictionary, persistentState, persistentStateLock);
		}

		protected byte[] Serialize(object value)
		{
			byte[] state = SilverlightSerializer.Serialize(value);
			return state;
		}

		protected T Deserialize<T>(byte[] data) where T : class
		{
			T result = SilverlightSerializer.Deserialize<T>(data);
			return result;
		}

		protected object Deserialize(byte[] data)
		{
			var result = SilverlightSerializer.Deserialize(data);
			return result;
		}

		void SaveState(
				IDictionary<string, object> stateDictionary,
				Dictionary<string, IStateAccessor> accessors,
				object propertiesLock)
		{
			lock (propertiesLock)
			{
				foreach (KeyValuePair<string, IStateAccessor> pair in accessors)
				{
					string stateKey = pair.Key;
					IStateAccessor accessor = pair.Value;

					object accessorValue = accessor.Value;

					if (accessorValue == null)
					{
						stateDictionary.Remove(stateKey);
						continue;
					}

					byte[] bytes;
					try
					{
						bytes = Serialize(accessorValue);
					}
					catch (Exception ex)
					{
						stateDictionary[pair.Key] = null;
						Debug.Assert(false,
									 "Unable to serialize state value. " + ex);
						continue;
					}

					stateDictionary[stateKey] = bytes;
				}
			}
		}

		void LoadState(
				IDictionary<string, object> stateDictionary,
				Dictionary<string, IStateAccessor> accessors,
				object propertiesLock)
		{
			lock (propertiesLock)
			{
				foreach (KeyValuePair<string, IStateAccessor> pair in accessors)
				{
					object stateValue;
					string stateKey = pair.Key;
					IStateAccessor accessor = pair.Value;

					if (!stateDictionary.TryGetValue(stateKey, out stateValue))
					{
						continue;
					}

					byte[] bytes = stateValue as byte[];

					if (bytes == null)
					{
						Debug.Assert(false, "state value is not a byte[]");
						continue;
					}

					object deserializedValue;
					try
					{
						deserializedValue = Deserialize(bytes);
					}
					catch (Exception ex)
					{
						string message = "Unable to deserialize bytes. " + ex;
						WriteToConsole(message);
						Debug.Assert(false, message);
						continue;
					}

					if (deserializedValue == null)
					{
						const string message = "Deserialized object should not be null.";
						WriteToConsole(message);
						Debug.Assert(false, message);
						continue;
					}

					try
					{
						accessor.Value = deserializedValue;
					}
					catch (Exception ex)
					{
						WriteToConsole("Unable to set state value. " + ex);
						continue;
					}
				}
			}
		}

		void WriteToConsole(string message)
		{
#if NETFX_CORE
			Debug.WriteLine(message);
#else
			Console.WriteLine(message);
#endif
		}

		class Accessor<T> : IStateAccessor
		{
			readonly Func<T> getter;
			readonly Action<T> setter;

			public Accessor(Func<T> getter, Action<T> setter)
			{
				this.getter = getter;
				this.setter = setter;
			}

			public object Value
			{
				get
				{
					return getter();
				}
				set
				{
					setter((T)value);
				}
			}
		}

		interface IStateAccessor
		{
			object Value { get; set; }
		}
	}
}